﻿using System.Windows.Data;

namespace EC3_6CLH.Model
{
    public class UInt16ToHexConverter : IValueConverter
    {
        // 正向转换：ushort -> 十六进制字符串
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is ushort number)
            {
                return $"0x{number:X4}"; // 格式化为 "0xFFFF"
            }
            return string.Empty;
        }

        // 反向转换：十六进制字符串 -> ushort
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is string hexString)
            {
                try
                {
                    // 移除可能的 "0x" 前缀
                    string cleanHex = hexString.Replace("0x", "").Replace("0X", "");
                    return System.Convert.ToUInt16(cleanHex, 16); // 按十六进制解析
                }
                catch
                {
                    return 0; // 解析失败时返回默认值（或抛出异常）
                }
            }
            return 0;
        }
    }
}